import ListModel from '../model/ListModel';
import VideoModel from '../model/VideoModel';

const webUrlStr = "https://www.kanying.org";
const websiteName = "看影"
const myRequest = require('request');
const xpath = require('xpath')
const dom = require('xmldom').DOMParser

function request(url, callback) {
	const headers = {
		'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36',
		'Access-Control-Allow-Origin': "*"
	};
	const options = {
		url: url,
		headers: headers,
		timeout: 10000
	};
	myRequest(options, callback)
}

function nodesReplace(title, strArr = []) {
	for (var i = 0; i < strArr.length; i++) {
		title = title.replace(strArr[i], "")
	}
	return title
}



export default {
	webUrlStr,
	websiteName,
	getIndexData(success,faile) {
		request(webUrlStr, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				body = body.replace(/<html\s.*?>/g, "<html>")
				let doc = new dom().parseFromString(body, 'text/xml')
				let divArr = ["1", "2", "3", "4"]
				let titleArr = ["电影", "电视剧","综艺", "动漫"]
				var resultArr = []
				// 循环爬取模块
				for (let i = 0; i < divArr.length; i++) {
					let item = divArr[i]
					let listModel = new ListModel()
					listModel.title = titleArr[i]
					listModel.more = true
					// 爬取具体的item
					let titleXpath =
						"/html/body/div[1]/div[2]/div["+item+"]/div/div/ul/li/div/a/@title"
					let urlXpath =
						"/html/body/div[1]/div[2]/div["+item+"]/div/div/ul/li/div/a/@href"
					let imgXpath =
						"/html/body/div[1]/div[2]/div["+item+"]/div/div/ul/li/div/a/@data-original"
					let updateXpath =
						"/html/body/div[1]/div[2]/div["+item+"]/div/div/ul/li/div/a/span[3]/text()"
					let titleNodes = xpath.select(titleXpath, doc)
					let urlNodes = xpath.select(urlXpath, doc)
					let imgNodes = xpath.select(imgXpath, doc)
					let updateNodes = xpath.select(updateXpath, doc)
					var videoArr = []
					for (let j = 0; j < titleNodes.length; j++) {
						const model = new VideoModel();
						var title = titleNodes[j].toString()
						title = title.replace('title="',"")
						title = title.replace('"',"")
						var url = urlNodes[j].toString()
						url = url.replace('href=','')
						url = url.replace('"')
						url = webUrlStr+url
						 url = url.replace(" ","")
						var image = imgNodes[j].toString()
						console.log(image)
						image = image.replace('data-original="','')
						image = image.replace('"','')
						image = webUrlStr+image
						image = image.replace(" ","")
						console.log(image)
						let update = updateNodes[j].toString()
						model.name = title
						model.picImg = image
						model.update = update
						model.detailUrl = url
						videoArr.push(model)
					}
					listModel.list = videoArr
					resultArr.push(listModel)
				}
				success(resultArr)
			}else{
				console.log("加载失败")
				faile(error)
			}
		})
	}
}